import React from 'react';
import {Table, Row, Col, message, Form, Button, Divider, Affix, Alert, Spin} from 'antd';
import PropTypes from 'prop-types';
import {formatMessage} from './intl';
import {
    PAGE, TABLE,
    PAGINATION_OPTIONS,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT,
    ROWSELECTION_FIXED_COLUMN_WIDTH
} from '../constants';
import TextInput from 'Shared/components/TextInput';
import {conventSorter} from '../utils';
import styles from './style.css';
import WrappedTag from '../common/WrappedTag';
import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {
    getDealersByPage,
    getDealersByCategory,
    saveDealerCondition,
    getDealersByQuery,
    clearDealer
} from './actions';

const FormItem = Form.Item;
const FORM_OPTIONS_COL = {
    xxl: 8,
    xl: 8,
};

const FORM_OPTIONS_ITEM = {
    labelCol: {
        xxl: {span: 4},
        xl: {span: 6},
        md: {span: 4}
    },
    wrapperCol: {
        xxl: {span: 20},
        xl: {span: 18},
        md: {span: 20}
    },
    colon: true
};
const FORM_OPTIONS_BUTTON = {
    wrapperCol: {
        xxl: {
            span: 20,
            offset: 4
        },
        xl: {
            span: 18,
            offset: 6
        },
        md: {
            span: 20,
            offset: 4
        }
    }
};

export class DealerTable extends React.PureComponent {
    state = {
        selectedRowKeys: [],
        selectedRows: [],
        marketDepartmentId: null,
        isExpand: false,
        loading: false
    };
    componentWillUnmount() {
        this.props.clearDealer();
    }
    onChangeRadio = (selectedRowKeys, selectedRows) => {
        this.setState({
            selectedRowKeys,
            selectedRows
        });
    }
    onCloseTag = () => {
        this.setState({
            selectedRowKeys: [],
            selectedRows: []
        });
    }
    onChangeSort = (pagination, filters, sorter) => {
        if(pagination.current - 1 === this.props.pageIndex && pagination.pageSize === this.props.pageSize)
            this.props.onChangeSort({
                ...conventSorter(sorter),
                pageIndex: PAGE.index
            });
    };
    onClickNumber = () => {
        const {isExpand} = this.state;
        this.setState({
            isExpand: !isExpand
        });
    }

    onSubmit = () => {
        if(!this.state.selectedRows.length)
            return message.warn(formatMessage({
                id: 'vehicleInfoSelect.radioMessage',
                defaultMessage: '请选择总代子公司'
            }));
        this.props.onSelect(this.state.selectedRows[0]);
    }
    render() {
        const columns = [{
            title: '编号',
            dataIndex: 'code',
            sorter: true
        },
        {
            title: '名称',
            dataIndex: 'name',
        },
        {
            title: '简码',
            dataIndex: 'shortCode'
        },
        {
            title: '简称',
            dataIndex: 'shortName'
        },
        {
            title: '国家',
            dataIndex: 'countryName'
        },
        {
            title: '城市',
            dataIndex: 'provinceName'
        },
        {
            title: '地址',
            dataIndex: 'cityName'
        }];
        const pagination = {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.pageIndex + 1,
            onShowSizeChange: this.props.onPageSizeChange,
            onChange: this.props.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const onRow = record => ({
            onDoubleClick: () => {
                // 双击选中
                this.props.onSelect(record);
            }
        });
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        const rowSelection = {
            type: 'radio',
            fixed: true,
            columnWidth: ROWSELECTION_FIXED_COLUMN_WIDTH,
            onChange: this.onChangeRadio,
            selectedRowKeys: this.state.selectedRowKeys,
        };
        const selectTag = (<span>{formatMessage({
            id: 'vehicleContactSelectPanel.selectTag',
            defaultMessage: '，已选择'
        })} {this.state.selectedRows.map(tag =>
            <WrappedTag key={tag.id} id={tag.id} closable onClose={this.onCloseTag}>
                {tag.name}
            </WrappedTag>)}</span>);
        const alertMessage = (<div>
            <Row>
                <Col span={18}><span>{formatMessage({
                    id: 'vehicleContactSelectPanel.alertMessage',
                    defaultMessage: '可以双击行选择'
                })}</span>{this.state.selectedRows.length ? selectTag : ''}</Col>
                <Col span={6} className="col-align-right">
                    <Button type="primary" size="small" onClick={this.onSubmit}>确认</Button>
                </Col>
            </Row>
        </div>);
        return (
            <Spin tip={formatMessage({
                id: 'dealerTable.tip',
                defaultMessage: '总代子公司查询'
            })} spinning={this.state.loading}>
                <Form className="form-standard">
                    <Row>
                        <Col {...FORM_OPTIONS_COL}>
                            <FormItem key="code" label={formatMessage({
                                id: 'dealerTable.code',
                                defaultMessage: '编号'
                            })} {...FORM_OPTIONS_ITEM}>
                                <TextInput
                                    name="code"
                                    onPressEnter={this.props.handleFilterPressEnter}
                                    value={this.props.conditions.code}
                                    onBlur={this.props.onConditionsChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS_COL}>
                            <FormItem key="name" label={formatMessage({
                                id: 'dealerTable.name',
                                defaultMessage: '名称'
                            })} {...FORM_OPTIONS_ITEM}>
                                <TextInput
                                    name="name"
                                    onPressEnter={this.props.handleFilterPressEnter}
                                    value={this.props.conditions.name}
                                    onBlur={this.props.onConditionsChange} />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col {...FORM_OPTIONS_COL}>
                            <FormItem key="shortCode" label={formatMessage({
                                id: 'dealerTable.shortCode',
                                defaultMessage: '简码'
                            })} {...FORM_OPTIONS_ITEM}>
                                <TextInput
                                    name="shortCode"
                                    onPressEnter={this.props.handleFilterPressEnter}
                                    value={this.props.conditions.shortCode}
                                    onBlur={this.props.onConditionsChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS_COL}>
                            <FormItem key="shortName" label={formatMessage({
                                id: 'dealerTable.shortName',
                                defaultMessage: '简称'
                            })} {...FORM_OPTIONS_ITEM}>
                                <TextInput
                                    name="shortName"
                                    onPressEnter={this.props.handleFilterPressEnter}
                                    value={this.props.conditions.shortName}
                                    onBlur={this.props.onConditionsChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS_COL}>
                            <FormItem key="btn" {...FORM_OPTIONS_BUTTON}>
                                <Button key="query" type="primary" onClick={this.props.querySearch} loading={this.props.loading}>{formatMessage({
                                    id: 'dealerTable.btn.query',
                                    defaultMessage: '查询'
                                })}</Button>
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
                <Divider className={styles.divider} />
                <Affix offsetTop={0} className={styles.alertMargin}><Row>
                    <Alert message={alertMessage} type="info" showIcon />
                </Row></Affix>
                <Table
                    className="white-space-nowrap"
                    rowKey="id"
                    dataSource={this.props.dealers}
                    columns={columns}
                    pagination={pagination}
                    onRow={onRow}
                    loading={this.props.loading}
                    onChange={this.onChangeSort}
                    rowSelection={rowSelection}
                    locale={locale}
                    {...TABLE} />
            </Spin>
        );
    }
}

DealerTable.propTypes = {
    clearDealer: PropTypes.func.isRequired,
    conditions: PropTypes.object.isRequired,
    dealers: PropTypes.array.isRequired,
    errorMessage: PropTypes.string.isRequired,
    handleFilterPressEnter: PropTypes.func.isRequired,
    loading: PropTypes.bool.isRequired,
    querySearch: PropTypes.func.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    onCloseTag: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onPageIndexChange: PropTypes.func.isRequired,
    onPageSizeChange: PropTypes.func.isRequired,
    onSelect: PropTypes.func.isRequired,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
};

const getDealers = selectorFactory(['page', 'domainData', 'dealers', 'data']);
const getCondition = selectorFactory(['page', 'appState', 'queryConditionForDealer']);
const mapStateToProps = state => ({
    dealers: getDealers(state),
    conditions: getCondition(state),
    loading: state.getIn(['page', 'domainData', 'dealers', 'isFetching']),
    errorMessage: state.getIn(['page', 'domainData', 'dealers', 'message']),
    total: state.getIn(['page', 'domainData', 'dealers', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySortForDealer', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySortForDealer', 'pageSize'])
});

const mapDispatchToProps = dispatch => ({
    onPageSizeChange: (pageIndex, pageSize) => dispatch(getDealersByPage({
        pageIndex: PAGE.index,
        pageSize
    })),
    onPageIndexChange: pageIndex => dispatch(getDealersByPage({
        pageIndex: pageIndex - 1,
    })),
    onChangeSort: option => dispatch(getDealersByPage(option)),
    onCloseTag: () => dispatch(getDealersByCategory()),
    onConditionsChange: (value, name) => dispatch(saveDealerCondition(name, value)),
    querySearch: () => dispatch(getDealersByQuery()),
    handleFilterPressEnter: (value, name) => {
        dispatch(saveDealerCondition(name, value));
        dispatch(getDealersByQuery());
    },
    clearDealer: () => dispatch(clearDealer())
});

export default connect(mapStateToProps, mapDispatchToProps)(DealerTable);
